package com.effectivsocial.web.controller;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.data.domain.PageRequest;

import com.effectivsocial.domain.Application;
import com.effectivsocial.service.api.ApplicationService;

public class ApplicationLazyModel  extends LazyDataModel<Application> {
private static final long serialVersionUID = 1L;
	
	private ApplicationService applicationService;
	
	public ApplicationLazyModel(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}

	@Override
	public List<Application> load(int startingAt, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
		int page = startingAt / pageSize;
		PageRequest request = new PageRequest(page, pageSize);
		
		return applicationService.findByDeleted(request,false);
		
	}

	@Override
	public Application getRowData(String rowKey) {
		return applicationService.findOne(rowKey);
	}

	@Override
	public Object getRowKey(Application application) {
		return application.getId();
	}
	
	@Override
    public int getRowCount() {
        return (int) applicationService.count();
    }
	
	@Override
	public void setRowIndex(int rowIndex) {
		/*
		 * The following is in ancestor (LazyDataModel): this.rowIndex =
		 * rowIndex == -1 ? rowIndex : (rowIndex % pageSize);
		 */
		if (rowIndex == -1 || getPageSize() == 0) {
			super.setRowIndex(-1);
		} else
			super.setRowIndex(rowIndex % getPageSize());
	}
}
